package com.jams.goodox.activity.home;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.jams.goodox.BaseFragment;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.TownApplicationLike;
import com.jams.goodox.adapter.OnlineShoppingCommentAdapter;
import com.jams.goodox.entity.OnlineShoppingCommentBean;
import com.jams.goodox.net.BaseEntity;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.HomeService;
import com.jams.goodox.utils.CollectionUtils;
import com.jams.goodox.widget.NoScrollGridView;
import com.jams.goodox.widget.mannger.RefreshLinearLayoutManager;
import com.jams.library.commonAdapter.ListCommonAdapter;
import com.jams.library.commonAdapter.ListCommonViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * Created by Administrator on 2017/10/5.
 */

public class GoodFragment extends BaseFragment {

    @Bind(R.id.tx_good_number)
    TextView txGoodNumber;
    @Bind(R.id.img_right_arrow)
    ImageView imgRightArrow;
    @Bind(R.id.tx_good_icon)
    TextView txGoodIcon;
    @Bind(R.id.relative_good_right)
    RelativeLayout relativeGoodRight;
    @Bind(R.id.comment_number_grid)
    NoScrollGridView commentNumberGrid;
    @Bind(R.id.recycle_view)
    RecyclerView recycleView;
    @Bind(R.id.convenientBanner_main)
    ConvenientBanner<GoodsBean.Mutiple> convenientBannerMain;
    @Bind(R.id.swipe_refresh)
    SwipeRefreshLayout refreshLayout;
    @Bind(R.id.tx_comment_grade)
    TextView tx_comment_grade;
    @Bind(R.id.fr_banner)
    FrameLayout frBanner;
    @Bind(R.id.img_shoucang)
    ImageView imgShoucang;
    @Bind(R.id.tx_shop_name)
    TextView txShopName;
    @Bind(R.id.relative_title)
    RelativeLayout relativeTitle;
    @Bind(R.id.tx_price_limit)
    TextView txPriceLimit;
    @Bind(R.id.tx_have)
    TextView txHave;
    @Bind(R.id.tx_shopping)
    TextView txShopping;
    @Bind(R.id.tx_address)
    TextView txAddress;
    @Bind(R.id.tx_comment)
    TextView txComment;

    private View rootView;
    private static final int ScrollTime = 3000;

    private ListCommonAdapter listCommonAdapter;
    private List<CommentBean> goodDetailBeanList;
    private List<OnlineShoppingCommentBean> data;

    private List<GoodsBean.Mutiple> focusBeanList;//焦点图列表
    private String id;
    private boolean isCollect;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null)
            rootView = inflater.inflate(R.layout.good_detail_fragment, container, false);
        ButterKnife.bind(this, rootView);
        init();
        id=getArguments().getString("id");
        getGoodDetail(getArguments().getString("id"));
        initViews();
        return rootView;
    }

    private void getGoodDetail(String id) {
        enqueue(createCallService(HomeService.class).getProductDetail(SePref.getToken(), id, ""), new RetrofitCallbackListener<GoodsBean>() {
            @Override
            public void onSuccess(Call<GoodsBean> call, GoodsBean result) {
                refreshLayout.setRefreshing(false);
                if (result.getData() == null || result.getData().getInfo() == null || result.getData().getComment() == null)
                    return;
                GoodsBean.Comment comment = result.getData().getComment();
                goodDetailBeanList.clear();
                goodDetailBeanList.add(new CommentBean("好评", comment.getType1()));
                goodDetailBeanList.add(new CommentBean("中评", comment.getType2()));
                goodDetailBeanList.add(new CommentBean("差评", comment.getType3()));
                goodDetailBeanList.add(new CommentBean("五星", comment.getType4()));
                goodDetailBeanList.add(new CommentBean("四星", comment.getType5()));
                listCommonAdapter.notifyDataSetChanged();
                tx_comment_grade.setText(comment.getRadio());
                data.clear();
                data.addAll(comment.getItem());
                adapter.notifyDataSetChanged();
                GoodsBean.Info info = result.getData().getInfo();
                txShopName.setText(info.getTitle());
                txPriceLimit.setText(info.getPrice());
                txHave.setText(info.getInventory());
                txShopping.setText(info.getSales());
                isCollect=info.isCollect();
                if(isCollect)imgShoucang.setImageResource(R.mipmap.icon_shoucang);
                else imgShoucang.setImageResource(R.mipmap.icon_shoucang_empty);
                setFocus(result.getData().getInfo().getMultiple());
            }

            @Override
            public void onError(String msg) {
                refreshLayout.setRefreshing(false);
            }
        });
    }

    private void init() {
        goodDetailBeanList = new ArrayList<>();
        focusBeanList = new ArrayList<>();
        listCommonAdapter = new ListCommonAdapter<CommentBean>(getActivity(), goodDetailBeanList, R.layout.comment_text_item) {
            @Override
            public void convert(ListCommonViewHolder helper, CommentBean item, int position) {
                helper.setText(R.id.tx_comment_number, String.format("%s(%s)", item.getCommentName(), item.getCommentNumber()));
            }
        };
        commentNumberGrid.setAdapter(listCommonAdapter);
        //页面滚动时停止banner滚动
        refreshLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_MOVE:
                        if (convenientBannerMain != null && convenientBannerMain.isTurning()) {
                            convenientBannerMain.stopTurning();
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        if (convenientBannerMain != null && !convenientBannerMain.isTurning()) {
                            convenientBannerMain.startTurning(ScrollTime);
                        }
                        break;
                }
                return false;
            }
        });
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getGoodDetail(id);
            }
        });
    }

    //设置焦点图
    private void setFocus(List<GoodsBean.Mutiple> newFocusList) {
        focusBeanList.clear();
        if (CollectionUtils.hasData(newFocusList)) {
            focusBeanList.addAll(newFocusList);
        }
        convenientBannerMain.setPages(
                new CBViewHolderCreator<ShopBeanViewHolder>() {
                    @Override
                    public ShopBeanViewHolder createHolder() {
                        return new ShopBeanViewHolder();
                    }
                }, focusBeanList)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator(new int[]{R.drawable.white_home_indicator, R.drawable.main_home_indicator})
                //设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                .setScrollDuration(1200);
        if (focusBeanList.size() == 1) {//单张不可滚动、不出现底部红点
            convenientBannerMain.setPointViewVisible(false);
            convenientBannerMain.setCanLoop(false);
            convenientBannerMain.stopTurning();
        } else {
            convenientBannerMain.setPointViewVisible(true);
            convenientBannerMain.setCanLoop(true);
            convenientBannerMain.startTurning(ScrollTime);
        }
        convenientBannerMain.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                startActivity(new Intent(getContext(), VideoActivity.class));
            }
        });
    }

    OnlineShoppingCommentAdapter adapter;

    private void initViews() {
        recycleView.setLayoutManager(new RefreshLinearLayoutManager(getActivity()));
        data = new ArrayList<>();
        adapter = new OnlineShoppingCommentAdapter(getActivity(), data);
        recycleView.setAdapter(adapter);
        ViewGroup.LayoutParams layoutParams=frBanner.getLayoutParams();
        layoutParams.height=TownApplicationLike.width;
        frBanner.setLayoutParams(layoutParams);

    }

    @Override
    public void onResume() {
        super.onResume();
        if (convenientBannerMain != null) {
            convenientBannerMain.startTurning(ScrollTime);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (convenientBannerMain != null) {
            convenientBannerMain.stopTurning();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick(R.id.img_shoucang)
    public void onClick() {
        collect();
    }

    private void collect(){
        enqueue(createCallService(HomeService.class).collect(SePref.getToken(), id ), new RetrofitCallbackListener<BaseEntity>() {
            @Override
            public void onSuccess(Call<BaseEntity> call, BaseEntity result) {
                isCollect=!isCollect;
                if(isCollect)imgShoucang.setImageResource(R.mipmap.icon_shoucang);
                else imgShoucang.setImageResource(R.mipmap.icon_shoucang_empty);
            }

            @Override
            public void onError(String msg) {

            }
        });
    }
}
